﻿using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using SoftwareLogistics.SharepointClient.Library;

namespace SoftwareLogistics.SharepointClient.Models
{
    public class SPList
    {
        public Guid ListId { get; set; }
        public Guid ViewId { get; set; }
        public string Name { get; set; }
        public string SiteName { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        
        private Dictionary<string, SPField> _fields;
        
        public event EventHandler GotLists;

        public Dictionary<string, SPField> Fields { get { return _fields; } }

        public SPList()
        {
            _fields = new Dictionary<string, SPField>();
        }

        public static SPList Create(XElement element)
        {            
            var list = new SPList()
            {
                ListId = new Guid((string)element.Attribute("ID")),
                Title = (string)element.Attribute("Title"),
                Description = (string)element.Attribute("Description"),
                Name = (string)element.Attribute("Name")
            };

            return list;
        }


        public void GetLists(string site)
        {
            var listService = new SoftwareLogistics.SharepointClient.Library.ListsService.ListsSoapClient();
            string url = string.Format("http://slsys.homeip.net:8000/{0}/_vti_bin/lists.asmx", site);

            listService.Endpoint.Address = new System.ServiceModel.EndpointAddress(new Uri(url));
            listService.CookieContainer = Common.AuthService.GetCookieJar;

            listService.GetListCollectionCompleted += (sndr, args) =>
            {
                IEnumerable<XElement> rows = args.Result.Descendants(XName.Get("List", "http://schemas.microsoft.com/sharepoint/soap/"));
                var listservice = (from element in rows
                            select SPList.Create(element)).ToList();

                var eventArgs = new GotListsEventArgs();
                eventArgs.Lists = new Dictionary<string, SPList>();

                foreach (var list in listservice)
                    eventArgs.Lists.Add(list.Name, list);

                GotLists(this, eventArgs);
            };

            listService.GetListCollectionAsync();

        }
    }

    public class GotListsEventArgs : EventArgs
    {
        public Dictionary<string, SPList> Lists { get; set; }
    }
}
